package com.dxj1992.handler;

import com.alibaba.fastjson.JSONObject;
import com.dxj1992.entity.SteamBalances;
import com.dxj1992.service.ISteamBalancesService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import static java.nio.charset.StandardCharsets.UTF_8;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class TestServiceHandler implements QueueTaskHandler {

    private ISteamBalancesService steamBalancesService;
    private SteamBalances steamBalances;

    @Override
    public void processData() {
        String url = steamBalances.getUrl();
        if (!url.contains("http")) {
            return;
        }
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://128.1.131.90/api/getGoodsPrice?url=" + url);
        try {
            CloseableHttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String jsonStr = EntityUtils.toString(response.getEntity(), UTF_8);
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                Integer status = (Integer) jsonObject.get("status");
                if (status != 1) {
                    throw new RuntimeException("接口异常");
                }
                String content = String.valueOf(jsonObject.get("content"));
                JSONObject jsonObject2 = JSONObject.parseObject(content);
                String buyOrderSummary = (String) jsonObject2.get("buy_order_summary");

                Document document = Jsoup.parse(buyOrderSummary);
                Element first = document.getElementsByClass("market_commodity_orders_header_promote").last();
                String text = first.text();
                String price = text.replace("$", "");
                System.out.println(price);
                steamBalances.setPrice(Double.parseDouble(price));
                steamBalancesService.updateById(steamBalances);
            } else {
                System.out.println("请求失败");
            }
        } catch (Exception e) {
            log.warn("错误：" + e.getMessage() + "行：" + e.getLocalizedMessage());
            e.printStackTrace();
        }
    }
}